package com.lagou.work4;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientTest {

    public static void main(String[] args) {
        Socket s = null;
        ObjectOutputStream ps = null;
        Scanner sc = null;
        ObjectInputStream br = null;

        User user = null;

        try {
            // 1.创建Socket类型的对象并提供服务器的主机名和端口号
            s = new Socket("127.0.0.1", 18888);
            System.out.println("连接服务器成功！");

            // 2.使用输入输出流进行通信
            sc = new Scanner(System.in);
            ps = new ObjectOutputStream(s.getOutputStream());
            br = new ObjectInputStream(s.getInputStream());
            while (true) {
                // 实现客户端发送的内容由用户从键盘输入
                System.out.println("请输入用户名及密码(以空格进行分割)：");
                String str1 = sc.next();
                String str2 = sc.next();
                // 实现客户端向服务器发送UserMessage对象"
                ps.writeObject(new UserMessage("check", new User(str1,str2)));
                System.out.println("客户端发送数据内容成功！");
                // 实现接收服务器发来的字符串内容并打印
                UserMessage userMessage = (UserMessage) br.readObject();
                System.out.println("服务器回发的对象是：" + userMessage);
                if ("success".equals(userMessage.getType())) {
                    System.out.println("admin登陆成功");
                    break;
                }else {
                    System.out.println("admin登陆失败，请重新登陆");
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭Socket并释放有关的资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ps) {
                try {
                    ps.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != sc) {
                sc.close();
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
